<?php
session_start();
require_once (__DIR__ . '/../inc/functions.php');

function IsLoggedIn()
{
	return UserId() != FALSE;
}

function UserId()
{
	if(!isset($_SESSION['User']))
		return FALSE;
	$user = $_SESSION['User'];
	if(!isset($user['id']))
		return FALSE;
	
	return $user['id'];
}

function UserName() {
  return isset($_SESSION['User']) && isset($_SESSION['User']['name']) ? $_SESSION['User']['name'] : false;
}

function UserLevel() {
  return isset($_SESSION['User']) && isset($_SESSION['User']['level']) ? $_SESSION['User']['level'] : false;
}

function User()
{
	if(!isset($_SESSION['User']))
		return FALSE;
	$user = $_SESSION['User'];
	return $user;	
}

function RequireLogin()
{
	global $rootUrl;
	if(!IsLoggedIn())
	{
		header("Location: $rootUrl/../W/Accounts/login?returnUrl=$_SERVER[REQUEST_URI]");
		die();
	}
}

function DoLogout() {
  unset($_SESSION['User']);
}

function DoLogin($email, $password) {
  if(!empty($password)) {
    
    // Check to see if email and password match
    $conn = GetConnection();
    $query = 'SELECT u.FirstName, u.LastName, k.Name
              FROM `2012Grad_Users` u, `2012Grad_ContactMethods` cm, `2012Grad_Keywords` k
              WHERE u.id = cm.User_id
                AND cm.Keyword_id = 7
                AND cm.Value = "' . $conn->real_escape_string($email) . '"
                AND u.password = SHA1("' . $conn->real_escape_string($password) . '")
                AND k.id = u.Keyword_id';
    
    // Get feedback
    $result = $conn->query($query);
    if ($row = $result->fetch_row()) {
      $_SESSION['User'] = array(
        'name'  => $row[0] . ' ' . $row[1],
        'id'    => $email,
        'level' => $row[2]
      );
      
      $conn->close();
      return true;
    }
    
    $conn->close();
    return array('password'=>'Wrong password');
  }
  else{
    return array('password'=>'Wrong password');
  }
}
